<!--
 * @Description: 发起流程
 * @Author: wangwangwang
 * @Date: 2020-08-07 13:34:47
 * @LastEditors: wangwangwang
 * @LastEditTime: 2021-03-18 11:22:44
-->
<template>
  <div class="pages_content taskCenter">
    <el-container>
      <el-header>
        <div>
          <el-button size="medium" class="bottom_all" style="margin-left: 0;" @click="saveSubmit()">保 存</el-button>
          <el-button size="medium" class="bottom_all_two" @click="sendSubmit">提 交</el-button>
          <!-- <el-button size="medium" class="botton_five" style="margin-left: 24px;">流程查看</el-button> -->
        </div>
      </el-header>
      <el-main class="tc-info">
        <div class="tc-title">
          <el-input v-model="flowsTitleData.title" placeholder="请输入标题" />
        </div>
        <div class="info-top">
          <div class="left">
            <span>单据号码：{{tipInfo.code}}</span>
            <span class="text">制单日期：{{tipInfo.currentDate}}</span>
          </div>
          <div class="right">
            <span>发起人：{{userInfo.userRealName}}</span>
            <span class="text">状态：申请</span>
          </div>
        </div>
        <el-form>
          <div v-for="item in flowsFormData" :key="item.id" class="from-row">
            <el-row>
              <template v-for="(list,index) in item.children">
                <el-col v-if="!list.isEmpty" :key="index" :style="{width:`${(list.width/defaultColNum)*100}%`}">
                    <template v-for="(list2, index2) in list.children">
                      <el-form-item v-if="list2.type" :key="index2" :label-width="`${list2.titleWidth/(list2.titleWidth*1+list2.contentWidth*1)*100}%`" :label="list2.title" :rules="[{required: list2.required,message: '数据不能为空',}]">
                        <el-input v-if="list2.type===1" v-model="list2.value" :rows="list2.rowHeight" class="input-list"></el-input>
                        <el-input v-if="list2.type===2||list2.type===8" v-model="list2.value" resize='none' type="textarea" :rows="list2.rowHeight"></el-input>
                        <div v-if="list2.type===3">
                          <el-radio-group v-model="list2.value">
                            <el-radio v-for="list3 in list2.dicList" :key="list3.id" :label="list3.id">{{list3.itemName}}</el-radio>
                          </el-radio-group>
                        </div>
                        <!-- <el-checkbox-group v-model="list2.value"  v-if="list2.type===4">
                          <el-checkbox v-for="list3 in list2.dicList" :value="list3.itemValue" :key="list3.id" :label="list3.itemName"></el-checkbox>
                        </el-checkbox-group> -->
                        <el-select v-if="list2.type===4" v-model="list2.value" multiple style="width:100%;" placeholder="请选择">
                          <el-option v-for="list3 in list2.dicList" :key="list3.id" :label="list3.itemName" :value="list3.id" />
                        </el-select>
                        <el-select v-if="list2.type===5" v-model="list2.value" style="width:100%;" placeholder="请选择">
                          <el-option v-for="list3 in list2.dicList" :key="list3.id" :label="list3.itemName" :value="list3.id" />
                        </el-select>
                        <el-date-picker v-if="list2.type===6" v-model="list2.value" style="width:100%;" :type="list2.timeType==='1'?'date':'datetime'" placeholder="选择日期">
                        </el-date-picker>
                        <div v-if="list2.type===7">
                          <FileComponent fileCode="flowsFile" :files="files" @deleteFile="deleteFile" @uplodeSuccess="uplodeSuccess" />
                        </div>
                      </el-form-item>
                    </template>
                </el-col>
              </template>
            </el-row>
          </div>
        </el-form>
      </el-main>
    </el-container>
    <approvalModal :approvalVisible='approvalVisible' :approvalNode='approvalNode' @sendApprovePerson="sendApprovePerson" @handleModal="handleModal"></approvalModal>
  </div>
</template>

<script>
import { getFlowsCode, saveWorkFlow, previewProcess, submitTask, getTaskDetails } from '@/api/task/flows';
import { getFormData } from '@/api/Signed/flows';
import { getDicsType } from '@/api/common';
import approvalModal from '@/components/WorkFlow/approvalModal';
import FileComponent from '@/components/File/fileComponent';
import { getUserInfo } from "@/utils/auth";
import addTab from "@/common/addTab.js";
export default {
  components: {
    approvalModal,
    FileComponent
  },
  data() {
    return {
      title: '',
      options: [],
      fileList: [],
      urlData: {},
      tipInfo: {},
      previewData: [],
      defaultColNum: 10,
      flowDetails: {}, // 改流程的所有信息
      processTaskId: '',
      form: {},
      approvalNode: [],
      approvalVisible: false,
      flowsTitleData: {},
      flowsFormData: [],
      files: [],
      userInfo: {},
      subordinateSystem: '',
    };
  },
  methods: {
    /**
     * @Description: 删除附件
     * @Param: 
     * @Author: wangwangwang
     */
    deleteFile (index) {
      this.files.splice(index, 1);
    },
    /**
     * @Description: 上传成功
     * @Param: 
     * @Author: wangwangwang
     */
    uplodeSuccess (data) {
      this.files.push(data);
    },
    afterRead() {
      let img_file = this.$refs.inputer;
      var formData = new FormData();
      var fileObj = img_file.files[0];
      if (fileObj.type !== 'image/jpeg' && fileObj.type !== 'image/png') {
        this.$notify({
          title: '提示',
          message: '请选择图片文件',
          duration: 1000
        });
        return;
      }
      formData.append('file', fileObj);
    },
    initData() { // 发起流程获取流程数据
      const params = {
        code: this.urlData.code,
      }
      // 获取流程编码
      getFlowsCode(params).then(res => {
        if (res.code === 1001) {
          this.tipInfo = res.data;
        }
      })
      const params2 = {
        processManagerId: this.urlData.id,
      }
      // 获取表单信息并展示
      getFormData(params2).then(res => {
        if (res.code === 1001) {
          this.flowDetails = res.data;
          /**
          * @Description: 格式化formStructureData，将code绑定到value上去
          * @Param: 
          * @Author: wangwangwang
          */
          this.previewData = JSON.parse(res.data.formStructureData);
          this.flowsTitleData = this.previewData[0].children[0].children[0]; // 构造流程标题
          const flowsFormData = this.previewData.filter((item, index) => { // 构造流程form数据
            if (index !== 0) {
              return item
            }
          });
          this.initDicTypeData(flowsFormData);
        }
      })
    },
    initData2 () { // 待发流程
      const params = {
        receiptNumber: this.$route.query.receiptNumber
      }
      this.flowDetails.processManagerId = this.$route.query.processManagerId
      this.tipInfo = {
        code: this.$route.query.receiptNumber,
        currentDate: this.$route.query.createTime
      }
      getTaskDetails(params).then(res => {
        if (res.code === 1001) {
          this.previewData = JSON.parse(res.data.content);
          this.flowsTitleData = this.previewData[0].children[0].children[0]; // 构造流程标题
          const flowsFormData = this.previewData.filter((item, index) => { // 构造流程form数据
            if (index !== 0) {
              return item
            }
          });
          this.initDicTypeData(flowsFormData);
        }
      })
    },
    /**
    * @Description: 查看数据，获取数据字典
    * @Param: 
    * @Author: wangwangwang
    */
    initDicTypeData(flowsFormData) {
      const newArry = [];
      flowsFormData.forEach((item) => {
        const { children } = item;
        children.forEach((item2) => {
          const { children } = item2;
          children.forEach((item3) => {
            if (!item3.isEmpty && (item3.type === 3 || item3.type === 4 || item3.type === 5)) {
              newArry.push(item3)
            }
          })
        })
      });
      const dicTypeString = newArry.map((item) => {
        return item.dataSourceCode
      });
      const params = {
        codes: dicTypeString.join(',')
      }
      getDicsType(params).then(res => {
        if (res.code === 1001) {
          for (let i in res.data) {
            flowsFormData.forEach((item) => {
              const { children } = item;
              children.forEach((item2) => {
                const { children } = item2;
                children.forEach((item3) => {
                  if (!item3.isEmpty && (item3.type === 3 || item3.type === 4 || item3.type === 5)) {
                    if (i === item3.dataSourceCode) {
                      item3.dicList = res.data[i].items;
                    }
                  }
                })
              })
            });
          }
          this.flowsFormData = flowsFormData;
        }
      })
    },
    /**
     * @Description: 保存流程获取
     * @Param: 
     * @Author: wangwangwang
     */
    saveSubmit(type) {
      return new Promise((resolve) => {
        const params = {
          taskType: 1,
          processManagerId: this.urlData.id,
          processManagerName: this.urlData.name,
          taskTypeName: this.urlData.systemName,
          processVersionId: this.urlData.versionId,
          taskName: this.flowsTitleData.title,
          taskStatus: 1,
          receiptNumber: this.tipInfo.code,
          subordinateSystem: this.tipInfo.subordinateSystem,
          formType: 1,
          taskFlow: {
            content: JSON.stringify(this.previewData),
          },
        }
        saveWorkFlow(params).then(res => {
          if (res.code === 1001) {
            this.processTaskId = res.data;
            if (!type) {
              this.$message({
                message: '保存成功!!!',
                type: 'success',
              })
            }
          }
        });
        resolve()
      });
    },
    /**
     * @Description: 传参获取审批人
     * @Param: 
     * @Author: wangwangwang
     */
    sendSubmit() {
      for (let i = 0; i < this.flowsFormData.length; i+=1) {
        const { children } = this.flowsFormData[i];
        for (let j = 0; j < children.length; j+=1) {
          const childrens = children[j].children;
          for (let k = 0; k < childrens.length; k+=1) {
            if (!childrens[k].isEmpty && childrens[k].code) {
              if (!childrens[k].value && childrens[k].required) {
                this.$message.warning(`请填写${childrens[k].title}`)
                return
              }
            }
          }
        }
      }
      this.saveSubmit(1).then(() => {
        const data = {};
        /**
        * @Description: 构造提交数据
        * @Param: 
        * @Author: wangwangwang
        */
        this.flowsFormData.forEach((item) => {
          const { children } = item;
          children.forEach((item2) => {
            const { children } = item2;
            children.forEach((item3) => {
              if (!item3.isEmpty && item3.code) {
                data[item3.code] = item3.value;
                data[`${item3.code}_type`] = 'string';
                data[`${item3.code}_old`] = '';
              }
            })
          })
        });
        const params = {
          processManagerId: this.flowDetails.processManagerId,
          processTaskContent: JSON.stringify(data)
        }
        previewProcess(params).then(res => {
          if (res.code === 1001) {
            this.approvalNode = res.data.nodeList.map((item) => {
              if (item ?.userSet ?.length) {
                return {
                  ...item,
                  showName: (item.userSet.map((item) => item.userName)).join(',', ),
                }
              } else {
                return item
              }
            });
            this.approvalVisible = true;
          }
        })
      })
    },
    handleModal(type) {
      if (type === 1) { // 关闭弹窗
        this.approvalVisible = false;
      } else { // 提交流程
        this.sureSubmit()
      }
    },
    sendApprovePerson(choisePerson, index) {
      const data = {
        showName: (choisePerson.map((item) => item.name)).join(','),
      }
      const newArry = this.approvalNode.map((item, idx) => {
        if (index === idx) {
          return {
            ...item,
            ...data,
            personList: choisePerson,
          }
        } else {
          return item
        }
      })
      this.approvalNode = newArry;
    },
    /**
    * @Description: 流程提交
    * @Param: 
    * @Author: wangwangwang
    */
    sureSubmit() {
      const data = {};
      /**
      * @Description: 构造提交数据
      * @Param: 
      * @Author: wangwangwang
      */
      this.flowsFormData.forEach((item) => {
        const { children } = item;
        children.forEach((item2) => {
          const { children } = item2;
          children.forEach((item3) => {
            if (!item3.isEmpty && item3.code) {
              data[item3.code] = item3.value;
              data.code0_type = 'string';
              data[`${item3.code}_old`] = '';
            }
          })
        })
      });
      const nodeList = this.approvalNode.map((item) => {
        if (item.personList) {
          const newArry = item.personList.map((items) => {
            return {
              organization: '',
              station: '',
              userId: items.id,
              userName: items.name,
            }
          })
          return {
            ...item,
            userSet: newArry
          }
        } else {
          return item
        }
      });
      for (let i = 0; i < nodeList.length; i += 1) {
        if (!nodeList[i] ?.userSet ?.length) {
          this.$message({
            type: 'warning',
            message: `请选择节点序号为${i}的审批人`,
          })
          return
        }
      }
      const params = {
        formStructureData: JSON.stringify(this.previewData),
        nodeList,
        processManagerId: this.flowDetails.processManagerId,
        processManagerName: this.urlData.name,
        processTaskContent: JSON.stringify(data),
        processTaskId: this.processTaskId,
        taskTypeName: this.urlData.systemName,
        processVersionId: this.urlData.versionId,
      }
      submitTask(params).then(res => {
        if (res.code === 1001) {
          this.$message({
            type: 'success',
            message: '流程提交成功！！！'
          });
          this.approvalVisible = false;
          addTab.$emit("remove", this.$route.name);
        }
      });
    }
  },
  mounted() {
    const { query } = this.$route;
    this.userInfo = getUserInfo();
    /**
     * @Description: 待发流程
     * @param {*}
     * @Author: wangwangwang
     */
    if (query.taskType * 1 === 2) {
      this.initData2()
      return
    }
    this.urlData = query
    this.initData();
  }
};
</script>
<style lang="scss">
.tc-title {
  .el-input--small .el-input__inner {
    height: 78px;
  }
  input {
    border: 0;
    border-radius: 4px;
    outline: none;
    text-align: center;
    font-weight: 500;
    font-size: 24px;
  }
  input:focus {
    outline: none;
    border: 0;
  }
  input::-webkit-input-placeholder {
    color: #000000;
  }
}
</style>
<style lang="scss" scoped>
.el-link {
  color: $bg_color;
}
.el-link:hover {
  color: $bg_color;
  opacity: 0.7;
}
.iconzu2197:hover {
  color: $bg_color;
}
.upload-item {
  width: calc(100% - 100px);
  display: flex;
  flex-wrap: wrap;
  .upload-item-text {
    cursor: pointer;
    padding: 5px 10px;
    margin: 0 10px 10px 10px;
    border: 1px solid #e1e5ed;
    border-radius: 4px;
    .iconhome_icon_txt {
      color: $bg_color;
      margin-right: 5px;
      font-size: 14px;
    }
    .iconzu2197:hover {
      color: $bg_color;
    }
    .iconzu2197 {
      margin-left: 5px;
      color: #c0c4cc;
      font-size: 14px;
    }
  }
}
.upload {
  padding: 5px 10px;
  margin: 0 10px 10px 0px;
  position: relative;
  .upload_input {
    width: 70px;
    position: absolute;
    opacity: 0;
    top: 0;
    left: 0;
  }
}
.upload:hover {
  opacity: 0.8;
}
.tc-info {
  background: #ffffff;
  border-radius: 4px;
}
.info-top {
  font-size: $font_size;
  color: #000000;
  @include discen_al;
  justify-content: space-between;
  height: 60px;
  border-bottom: 1px #e1e5ed solid;
  .left {
    @include discen_al;
    .text {
      margin-left: 100px;
    }
  }
  .right {
    @include discen_al;
    .text {
      color: $bg_color;
      margin-left: 50px;
    }
  }
}
.taskCenter {
  box-shadow: 0px 0px 0px;
  background: rgba(0, 0, 0, 0);
  .el-header {
    box-shadow: 0px 0px 6px rgba(0, 167, 84, 0.12);
    background: #ffffff !important;
    border-radius: 4px;
  }
  .el-main {
    box-shadow: 0px 0px 6px rgba(0, 167, 84, 0.12);
    margin-top: 20px;
  }
}
.from-row {
  margin-top: 20px;
}
.input-list{
  white-space:nowrap;
}
</style>
